package br.com.pd.invocation;

import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import br.com.pd.messaging.MessageIF;
import br.com.util.CriptografiaBase64;
import br.com.util.PropertiesLoader;

import com.thoughtworks.xstream.XStream;

public class Marshaller implements MarshallIF {
	
	private boolean encryption;
	
	public Marshaller(){
		this.encryption = Boolean.parseBoolean((PropertiesLoader.getInstance().getPropertie(PropertiesLoader.ENCRIPTION)));
	}
	
	
	// transforma uma mensagem String 
	public String marshall(MessageIF m){
		XStream converter = new XStream();
		String s = converter.toXML(m);
		if (this.encryption) {
			try {
				s = CriptografiaBase64.encrypt(s);
			} catch (BadPaddingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NoSuchPaddingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalBlockSizeException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InvalidAlgorithmParameterException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
//		System.out.println("Marshall : " );
//		System.out.println(s);
		return s;
	}
	

	// transforma uma string em mensagem
	public MessageIF unMarshall(String b){
		XStream converter = new XStream();
		if (this.encryption) {
			try {
				b = CriptografiaBase64.decrypt(b);
			} catch (BadPaddingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NoSuchPaddingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalBlockSizeException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InvalidAlgorithmParameterException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		MessageIF m = (MessageIF) converter.fromXML(b);
//		System.out.println("Unmarshall : " );
//		System.out.println(b);
//		System.out.println("result " + m);
		return m;
	}

}
